
from django.http import HttpResponse, Http404, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.core.exceptions import ObjectDoesNotExist



from myapp.models import Users


def index(req):
    print('进入index')
    print(reverse('getList')) # reverse通过路由名称反向解析路由
    print(reverse('view', args=[30]))
    print(reverse('fun', args=['2025', '05']))
    return HttpResponse("Hello World!1111")
# Create your views here.
def getList(req):
    # lists = Users.objects.all()
    # for item in lists:
    #     print(item)
    # return HttpResponse('list ...')
    try:
        ulist = Users.objects.all()
        context = {
            'userList': ulist
        }
        return render(req, 'myapp/users/index.html', context)
    except:
        return HttpResponse('没有用户信息...')

def view(req, id):
    return HttpResponse('view ...%d'%(id))
    # raise Http404('页面不存在')


def fun(request, year, month):
    print(request)
    return HttpResponse('fun ...%s-%s'%(year, month))


def test_redirect(request):
    print('通过reverse获取地址然后重定向跳转')
    redirectUrl = reverse('fun', args=['2025', '05'])
    return redirect(redirectUrl)


def create(request):
    # user = Users(name='test', age=18)
    # user.save()
    # return HttpResponse('create success')
    return render(request, 'myapp/users/create.html')


def createData(req):
    try:
        name = req.POST.get('name')
        age = req.POST.get('age')
        user = Users(name=name, age=age)
        user.save()
        return redirect(reverse('getList'))
    except:
        return HttpResponse('create fail')


def delete(request, id):
    try:
        user = Users.objects.get(id=id)
        user.delete()
        return redirect(reverse('getList'))
    except ObjectDoesNotExist:
        return HttpResponse('user is not exist')


def jsonData(request):
    dataList = [
        {'name': 'test1', 'age': 18},
        {'name': 'test2', 'age': 19},
        {'name': 'test3', 'age': 20},
    ]
    return JsonResponse(dataList, safe=False)


